/*****************************************************************************
 * base64enc.js
 *
 * A JavaScript implementation of the RFC 2045 base64 encoding.  Encodes only
 * typeable characters.
 *
 * Public functions:  String base64encode(str)
 *
 * Copyright (C) 2000 Blackboard, Inc.
 *****************************************************************************/

// To convert strings to a list of ascii values
var sAscii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var sAscii = sAscii + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

// To convert value to base64 alphabet
var sBase64Alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";


// Converts the 3 character string to 4 character base64 encoded
function base64encode_quantum(str)
{
  var strLen = str.length;
  
  // Create a 4 integer array for the 3 character "quantum"
  var aQuantum = new Array(4);
  
  // Read in the first, second, and third values
  var nFirst  = (strLen > 0 )? sAscii.indexOf(str.charAt(0)) + 32 : 0;
  var nSecond = (strLen > 1 )? sAscii.indexOf(str.charAt(1)) + 32 : 0;
  var nThird  = (strLen > 2 )? sAscii.indexOf(str.charAt(2)) + 32 : 0;

  // Convert 4 base64 values from the 3 character values
  aQuantum[0] = nFirst >> 2;
  aQuantum[1] = ((nFirst & 3) << 4) + (nSecond >> 4);
  aQuantum[2] = ((nSecond & 15) << 2) + (nThird >> 6);
  aQuantum[3] = nThird & 63;

  // Adjust for the padding in case there were not enough characters in the input str
  if ( strLen == 1 )
  {
    aQuantum[2] = 64;   // pad
    aQuantum[3] = 64;   // pad
  }
  else if ( strLen == 2 )
  {
    aQuantum[3] = 64;   // pad
  }
  
  // Create the base64 string
  var sRet = "";
  for (i=0; i<4; i++)
    sRet += sBase64Alpha.charAt(aQuantum[i]);
  
  // Return the result
  return sRet;
}


// Converts the input string into a base64 string
function base64encode(str)
{
    // Break up into 3 character quantums and convert
    var i, nFrom, nTo;
    var sRet = "";
    for (i=0; i<str.length; i+=3)
    {
        nFrom = i;
        nTo = (i+3 < str.length)? i+3 : str.length;
        sRet += base64encode_quantum(str.substr(nFrom,nTo));
    }
    return sRet;
}
